<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-alert
          title="添加商品信息"
          type="info"
          center
          show-icon
          :closable="false"
        >
        </el-alert>
      </el-row>
      <!-- 进度条 -->
      <el-steps
        :space="200"
        :active="activeTitle-0"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 和form-->
      <el-form
        :model="infoForm"
        :rules="infoFormRules"
        ref="infoFormRef"
        label-width="100px"
        label-position='top'
      >
        <el-tabs
          tab-position="left"
          v-model="activeTitle"
          :before-leave='leaveTab'
          @tab-click='tabClicked'
        >
          <el-tab-pane
            label="基本信息"
            name="0"
          >
            <el-form-item
              label="商品名称"
              prop="goods_name"
            >
              <el-input v-model="infoForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item
              label="商品价格"
              prop="goods_price"
            >
              <el-input v-model="infoForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item
              label="商品重量"
              prop="goods_weight"
            >
              <el-input v-model="infoForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item
              label="商品数量"
              prop="goods_number"
            >
              <el-input v-model="infoForm.goods_number"></el-input>
            </el-form-item>
            <!-- 级联选择器 商品分类 -->
            <el-cascader
              v-model="infoForm.goods_cat"
              :options="cats"
              @change="cascaderChange"
              :props="cascaderProps"
              placeholder="请选择分类"
              clearable
              change-on-select
            ></el-cascader>
          </el-tab-pane>

          <!-- 步骤二 动态参数-->
          <el-tab-pane
            label="商品参数"
            name="1"
          >
            <el-form-item
              v-for="item in manyParams"
              :key='item.attr_id'
            >
              <!-- 属性标题 -->
              {{item.attr_name}}
              <!-- 属性具体描述 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <!-- 此时，attr_vals是一个数组 -->
                <el-checkbox
                  border
                  :label="item2"
                  v-for="(item2,index2) in item.attr_vals"
                  :key="index2"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 步骤三 静态属性-->
          <el-tab-pane
            label="商品属性"
            name='2'
          >
            <el-form-item
              :label="item.attr_name"
              v-for="(item) in onlyParams"
              :key='item.attr_id'
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 步骤四上传图片 -->
          <el-tab-pane
            label="商品图片"
            name="3"
          >
            <!-- file-list:上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] -->
            <el-upload
              :action="uploadURL"
              :on-success='uploaded'
              :on-remove="handleRemove"
              :on-preview='previewPic'
              list-type="picture"
              :headers="headersObj"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button>
              <!-- 提示文本 -->
              <!-- <div
                slot="tip"
                class="el-upload__tip"
              >只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-tab-pane>

          <!-- 步骤五 -->
          <el-tab-pane
            label="标签内容"
            name="4"
          >
            <quill-editor v-model="infoForm.goods_introduce">
            </quill-editor>
            <el-button
              type="primary"
              @click="addGood"
            >添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片显示对话框 -->
    <el-dialog
      :visible.sync="imgDialogVisible"
      width="50%"
    >
      <img
        :src=theImgURL
        style="width:100%"
      >
    </el-dialog>
  </div>
</template>
<script>
// 引入lodash，调用其深拷贝方法
import _ from 'lodash'
export default {
  data() {
    return {
      // 激活的左边标签页和step
      activeTitle: 0,
      // 商品分类
      cats: [],
      // 添加商品的信息
      // goods_cat是一个数组和级联选择器绑定了，但是后台接口要求他是一个字符串
      infoForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属于的分类数组
        goods_cat: [],
        pics: [],
        // 商品内容
        goods_introduce: '',
      },
      infoFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
      },
      // 级联选择器相关属性绑定规则
      cascaderProps: {
        expandTrigger: 'hover',
        children: 'children',
        label: 'cat_name',
        // value: 'goods_cat',
        value: 'cat_id',
      },
      // 动态参数列表
      manyParams: [],
      // 静态属性
      onlyParams: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headersObj: {
        Authorization: window.sessionStorage.getItem('browserToken'),
      },
      // 对话框图片路径
      theImgURL: '',
      imgDialogVisible: false,
    }
  },
  // 计算属性
  computed: {
    theCatID() {
      if (this.infoForm.goods_cat.length > 2) {
        return this.infoForm.goods_cat[this.infoForm.goods_cat.length - 1]
      } else {
        return null
      }
    },
  },
  methods: {
    async getCats() {
      let { data: res } = await this.$axios.get('categories')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cats = res.data
    },
    // type是only或者是many
    async getParams(goods_cat, type) {
      let { data: res } = await this.$axios.get(
        `categories/${goods_cat}/attributes`,
        {
          params: {
            sel: type,
          },
        }
      )
      // console.log(res,200)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 动态参数需要加工，静态属性不需要加工
      // 加工数据
      if (type === 'many') {
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
      }
      // console.log(res.data,208);
      return res.data
    },
    cascaderChange() {
      console.log(this.infoForm.goods_cat)
      // 只允许选择三级分类
      if (this.infoForm.goods_cat.length < 3) {
        this.infoForm.goods_cat = []
      }
    },
    // 切换标签页
    leaveTab(activeName, oldActiveName) {
      // console.log(activeName,'new');
      // console.log(oldActiveName,'old');
      // console.info(this.infoForm.goods_cat)
      // return false;
      // 看看是否允许从第一页离开
      if (oldActiveName === '0' && this.infoForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        // console.log(168);
        return false
      }
    },
    async tabClicked() {
      // console.log(this.activeTitle)
      if (this.activeTitle === '1') {
        // console.log(194);
        // console.log(this.theCatID);
        this.manyParams = await this.getParams(this.theCatID, 'many')
        // console.log(this.manyParams);
      } else if (this.activeTitle === '2') {
        this.onlyParams = await this.getParams(this.theCatID, 'only')
        // console.log(this.onlyParams)
      }
    },
    // 上传图片
    // 上传成功
    uploaded(response, file, fileList) {
      // console.log(response, 'res');
      // console.log(response.data.tmp_path);
      //       tmp_path: "tmp_uploads\2a77a72c8a91e602d1e3d1230113303c.jpg"
      // url: "http://127.0.0.1:8888/tmp_uploads\2a77a72c8a91e602d1e3d1230113303c.jpg"
      // console.log(file, 'file');
      // console.log(fileList, 'fileList');
      if (response.meta.status !== 200) {
        return this.$error('上传图片失败！')
      }
      // 放进infoForm对象里
      let picObj = { pic: response.data.tmp_path }
      this.infoForm.pics.push(picObj)
      // console.log(this.infoForm.pics,'pics');
    },
    // 删除图片
    handleRemove(file, fileList) {
      // file.response.tmp_path
      // console.log(file);
      // console.log(file.response.data.tmp_path);
      // console.log(this.infoForm.pics);
      // 找到要删除的下标
      let index = this.infoForm.pics.findIndex(
        (item) => item.pic === file.response.data.tmp_path
      )
      // console.log(index);
      this.infoForm.pics.splice(index, 1)
      console.log(this.infoForm.pics)
    },
    // 预览图片
    previewPic(file) {
      console.log(file)
      this.theImgURL = file.response.data.url
      this.imgDialogVisible = true
    },
    // 添加商品
    addGood() {
      this.$refs.infoFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必须项！')
        // this.infoForm.goods_cat=this.infoForm.goods_cat.join(',')
        // 深拷贝
        let newInfoForm = _.cloneDeep(this.infoForm)
        newInfoForm.goods_cat = newInfoForm.goods_cat.join(',')
        // console.log(newInfoForm)
        // console.log(this.manyParams,354);
        let attrs = []
        // 动态参数
        // console.log(this.manyParams);
        this.manyParams.forEach((item) => {
          // console.log(item);
          attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') })
        })
        // 静态属性
        // console.log(this.manyParams, 'many')
        // console.log(this.onlyParams)
        // return;
        this.onlyParams.forEach((item) => {
          attrs.push({ attr_id: item.attr_id,
          attr_value:item.attr_vals })
        })
        console.log(attrs);
        newInfoForm.attrs=attrs;
        let {data:res}=await this.$axios.post('goods',newInfoForm)
        console.log(res);
        if(res.meta.status!==201){
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    },
  },
  created() {
    this.getCats()
  },
}
</script>
<style lang="less" scoped>
.el-steps {
  margin-top: 15px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.quill-editor {
  margin-bottom: 15px;
}
</style>
